from django.db import models
from django.utils.translation import gettext_lazy as _
import os
from django.conf import settings


def version_file_path(instance, filename):
    """生成版本文件的存储路径"""
    # 使用软件名称和版本号创建文件路径
    return f'versions/{instance.software.name}/{instance.version_number}/{filename}'


class Software(models.Model):
    """软件程序基本信息"""
    name = models.CharField(_('软件名称'), max_length=100)
    description = models.TextField(_('软件描述'), blank=True)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)

    class Meta:
        verbose_name = _('软件')
        verbose_name_plural = _('软件')

    def __str__(self):
        return self.name


class Version(models.Model):
    """软件版本信息"""
    STATUS_CHOICES = [
        ('draft', _('草稿')),
        ('published', _('已发布')),
        ('deprecated', _('已停用')),
    ]

    software = models.ForeignKey(Software, on_delete=models.CASCADE, related_name='versions', verbose_name=_('软件'))
    version_number = models.CharField(_('版本号'), max_length=50)
    release_notes = models.TextField(_('发布说明'))
    download_url = models.URLField(_('下载地址'), blank=True)  # 可以为空，用于外部下载链接
    version_file = models.FileField(_('版本文件'), upload_to=version_file_path, blank=True, null=True)  # 新增：上传文件
    file_size = models.BigIntegerField(_('文件大小(字节)'), blank=True, null=True)  # 新增：文件大小
    status = models.CharField(_('状态'), max_length=20, choices=STATUS_CHOICES, default='draft')
    is_force_update = models.BooleanField(_('强制更新'), default=False)
    min_version = models.CharField(_('最低兼容版本'), max_length=50, blank=True)
    release_date = models.DateTimeField(_('发布时间'), null=True, blank=True)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)

    class Meta:
        verbose_name = _('版本')
        verbose_name_plural = _('版本')
        ordering = ['-created_at']
        unique_together = ['software', 'version_number']

    def __str__(self):
        return f"{self.software.name} - {self.version_number}"

    def save(self, *args, **kwargs):
        # 如果上传了文件，自动计算文件大小
        if self.version_file:
            self.file_size = self.version_file.size
            # 如果没有设置下载地址，使用上传文件的URL
            if not self.download_url:
                # 确保URL使用正斜杠
                file_url = self.version_file.url.replace('\\', '/')
                # 确保URL以/开头
                if not file_url.startswith('/'):
                    file_url = '/' + file_url
                self.download_url = file_url
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        # 删除版本时同时删除文件
        if self.version_file:
            if os.path.isfile(self.version_file.path):
                os.remove(self.version_file.path)
        super().delete(*args, **kwargs) 